home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 402 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: EU.net!sun4nl!ittpub!ittpub!nntp
  2. Newsgroups: comp.lang.c++
  3. Subject: Re: Static creator methods
  4. Message-ID: <1996Jan4.113320.1726@ittpub>
  5. From: wil@ittpub.nl (Wil Evers)
  6. Date: 4 Jan 96 11:33:19 WET
  7. References: <4ce6is$gpp@rdsunx.crd.ge.com>
  8. Distribution: world
  9. Nntp-Posting-Host: lintilla
  10.  
  11. In article <4ce6is$gpp@rdsunx.crd.ge.com>  
  12. kornfein@unconfigured.xvnews.domain (Mark Kornfein) writes:
  13. > I have some code that I inherited that uses static creator methods
  14. > (functions) to create new instances of a class. Anotherwords the "new
  15. > ClassConstructor" is called from a static method instead of directly.
  16. > I assumed that this was done because the original coder did not
  17. > understand C++. Now I read a manual for a class library that 
  18. > recommends always using these, but does not say why.
  19. > What are the advantages/disadvantages of encapsulating the 
  20. > instantiation of objects this way?
  21.  
  22. There are quite a few idioms (e.g. envelope/letter) that assume instances  
  23. of particular classes are always allocated on the heap. In such cases I  
  24. usually put a few static creator functions in that class, and declare the  
  25. constructors as `protected' instead of `public'. As a result, the only way  
  26. to instantiate objects of that class is through one of the creator  
  27. functions.
  28.  
  29. An additional advantage of instatiating objects this way is that the  
  30. creator function may return a pointer to an object of some class derived  
  31. from the class in which the creator function is declared. This way,  
  32. differences in behaviour can be implemented through polymorphism without  
  33. the instantiating user having to know or worry about it.
  34.  
  35. - Wil
  36.